<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WAMP Client with Camera Control and Video Stream</title>
<script src="https://cdn.bootcdn.net/ajax/libs/autobahn/22.10.1/autobahn.min.js"></script>
<style>
  #video-container {
    width: 640px;
    height: 480px;
  }
  video {
    width: 100%;
    height: auto;
    outline: auto;
  }
  button {
    margin-bottom: 10px;
  }
</style>
</head>
<body>

<h2 id = title2>连接WAMP 服务器失败，请确保服务器开启，再刷新重连</h2>

<div id="video-container">
  <img id="video" src = "https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top-e3b63a0b1b.png"></img>
  <!-- <video id="video" autoplay></video> -->
</div>

<button id="open-camera-btn">Open Camera</button>
<button id="close-camera-btn">Close Camera</button>

<script>
// 定义WAMP连接配置
const wampConfig = {
  url: 'ws://127.0.0.1:8080/ws', // 替换为您的WAMP路由器URL
  realm: 'realm1' // 替换为您的realm名称
};
const OpenCamTopic = "ICamServices.OpenCam";
const CloseCamTopic = "ICamServices.CloseCam";
const video = document.getElementById('video');
const title2 = document.getElementById('title2');

// 初始化WAMP连接
const connection = new autobahn.Connection(wampConfig);

// 连接成功后的回调函数
connection.onopen = function (session) {
  console.log("Connected to WAMP router.");
title2.innerHTML = "成功连接到 WAMP router";
  

// 订阅摄像头影像事件
session.subscribe(OpenCamTopic, function(res) {

          //const blob = new Blob(res, { type: 'image/jpeg' }); // 假设图像是JPEG格式
          //video.src = URL.createObjectURL(blob);

        video.src =   "data:image/webp;base64," + res[0];
//video.srcObject = res[0];//MediaStream
//video不能直接添加图片
      }).catch(function(error) {
        console.error("Subscribe to OpenCamTopic stream failed:", error);
      });
 
      
      session.subscribe(CloseCamTopic, function(res) {
        console.log(res);
        video.src = "https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top-e3b63a0b1b.png";
      }).catch(function(error) {
        console.error("Subscribe to CloseCamTopic failed:", error);
      });
      

  // 打开摄像头按钮事件
  document.getElementById('open-camera-btn').addEventListener('click', function() {
    session.call(OpenCamTopic).then(function(res) {
      console.log("Camera opened :", res);
    }).catch(function(error) {
      console.error("Failed to open camera:", error);
    });
  });

  // 关闭摄像头按钮事件
  document.getElementById('close-camera-btn').addEventListener('click', function() {
      session.call(CloseCamTopic).then(function(res) {
        console.log("Camera closed:",res);
      }).catch(function(error) {
        console.error("Failed to close camera:", error);
      });

  });

  // 其他代码...
};

// 连接错误时的回调函数
connection.onerror = function (error) {
  console.error("Connection error:", error);
};

// 开始连接
connection.open();
</script>

</body>
</html>